package com.jiyun.wait.config;
import com.jiyun.wait.service.impl.WaitServiceImpl;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;


@Slf4j
@ServerEndpoint(value = "/api/websocket/{userId}")
@Component
public class WebSocketServer {
    private static Logger l= LoggerFactory.getLogger(WebSocketServer.class);
    private String userId;

   @Autowired
   private RabbitTemplate rabbitTemplate;

    private static WaitServiceImpl ns;

    //通过类注入的方式注入rabbitTemplate；
    @Autowired
    public void setWaitServiceImpl(WaitServiceImpl noticeService) {
        WebSocketServer.ns = noticeService;
    }


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId=userId;
        log.info("连接建立");
    }
    @OnClose
    public void onClose() {
        log.info("连接关闭");
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            log.info("收到消息,{}", message);
            int i = ns.waitPeople();
            log.info("当前队列中的消息数为:{}",i);
            if (i == 0) {
                int i1 = ns.selectOrderStatusIsTake(message);
                if (i1==0){
                    //广播消息到前台
                    session.getBasicRemote().sendText("轮到你了");
                    //关闭连接
                    onClose();
                }
            } else {
                session.getBasicRemote().sendText("还有人在排队");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
